/*
  A header file for common functions needed by Page Replacement behavior
  tests. Should be included in all test files.
 */
#ifndef _PAGE_ALGO_COMMON_H
#define _PAGE_ALGO_COMMON_H

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <linux/pgfltstats.h>


#define pgfltstats(x, y, z)         syscall( 304, x, y, z )

#define NUM 90000
#define SIZE 4080

char * chunks[NUM];

/* 
   Read and write each location in the page list in the range [low,hi)
   twice. This ensures that the page is marked as active by Linux.

   Access the pages in specificed order. So, if low < hi, then access
   low, low+1, . . ., hi-2, hi-1. But, if hi < low, then access
   hi, hi-1, hi-2, . . ., low+2, low + 1.

 */
void my_access( int low, int hi ) {

  int i, j, k;
  if ( low < hi ) {
    // Low to high index access
    for ( i = low; i < hi; i ++ ){
      for ( j = SIZE / 2; j < SIZE / 2 + 5; j ++ ){
	for ( k = 0; k < 2; k++) {
	  if ( chunks[i][j] == 'a' ) {
	    chunks[i][j] == 'b';
	  }
	  else {
	    chunks[i][j] == 'a';
	  }
	}
      }
    }
  }
  else {
    // High to low index access
    for ( i = low-1; i >= hi; i -- ){
      for ( j = SIZE / 2; j < SIZE / 2 + 5; j ++ ){
	for ( k = 0; k < 2; k++) {
	  if ( chunks[i][j] == 'a' ) {
	    chunks[i][j] == 'b';
	  }
	  else {
	    chunks[i][j] == 'a';
	  }
	}
      }
    }
  }

}

/*
  Allocate NUM pages and store them in a global array. We may not
  ever actually use this many pages, but this ensures that we have enough
  for any different test or access pattern.
 */
void init() {
  int i;
  for ( i = 0; i < NUM; i ++ ) {
    chunks[i] = malloc( SIZE );
    if ( ! chunks[i] ) {
      perror("malloc");
      exit(1);
    }
  }
  
}

#endif
